package controller;


import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/getAuthor")
public class AuthorInfoServlet extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        String blogId = req.getParameter("blogId");

        if (blogId == null) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("请求中没有 quary String");
            return;
        }
        BlogDao blogDao = new BlogDao();
        Blog blog = blogDao.getBlog(Integer.parseInt(blogId));
        if (blog == null) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("没有该篇博客！");
            return;
        }

        int userId = blog.getUserId();
        UserDao userDao = new UserDao();
        User user = userDao.getUserById(userId);
        if (user == null) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("该用户不存在！");
            return;
        }

        user.setPassword("");
        resp.setStatus(200);
        String userJson = objectMapper.writeValueAsString(user);
        resp.setContentType("application/json; charset=utf8");
        resp.getWriter().write(userJson);
    }
}
